import { createRouter, createWebHistory } from "vue-router";
import store from "@/store";
import routesStatic from "./routes-static";
// 配置路由
const router = createRouter({
    history: createWebHistory(),
    routes: routesStatic,
});

// 配置白名单路由name集合，在这里配置的是不需要登录的
const whiteNames = ['login', '403', '404'];

// 路由的前置守卫，用来做登录拦截
router.beforeEach(async (to, from) => {
    // 非白名单的路由
    if (!whiteNames.includes(to.name)) {
        // 做登陆状态的校验
        console.log('store', store);
        const token = store.state.user.token;
        if (!token) {
            return {
                name: 'login',
                query: {
                    redirect: to.fullPath
                },
            };
        };

        // // 判断路由权限
        // const routes = store.state.user.routes;
        // if (to.name != 'index' && !routes.includes(to.path)) {
        //     // 没有访问权限
        //     return { name: '403' };
        // }

        const isAdd = store.state.user.isAdd;
        if (!isAdd) {
            // 修改isAdd的状态为true
            store.commit("user/setIsAdd", true)
            // 获取用户的个人信息
            const routes = await store.dispatch("user/getPerson");
            // 动态添加；路由
            routes.forEach(route => {
                router.addRoute('index', {
                    path: route.router,
                    component: () => import(`../${route.viewPath}`)
                })
            })
            // 解决动态添加路由刷新后白屏问题,触发重定向
            return to.fullPath;
        }
    };
});

export default router